package com.reactnativerecorderview;

import android.media.AudioFormat;
import android.media.MediaRecorder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.reactnativerecorderview.idealrecorder.IdealRecorder;
import com.reactnativerecorderview.idealrecorder.StatusListener;
import com.reactnativerecorderview.idealrecorder.utils.Log;

import java.io.File;

public class RecordAudioModule extends ReactContextBaseJavaModule {

  private static ReactApplicationContext reactContext;
  private static String saveFilePath;
  private IdealRecorder idealRecorder;
  private IdealRecorder.RecordConfig recordConfig;

  public RecordAudioModule(ReactApplicationContext context){
    super(context);
    reactContext = context;
    saveFilePath = getSaveFilePath();

  }

  @NonNull
  @Override
  public String getName() {
    return "RecordAudioManager";
  }

  @ReactMethod
  public void start() {
    if (idealRecorder == null){
      IdealRecorder.getInstance().init(reactContext);
      idealRecorder = IdealRecorder.getInstance();
      recordConfig = new IdealRecorder.RecordConfig(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);

    }
    idealRecorder.setRecordFilePath(saveFilePath);
//    idealRecorder.setWavFormat(false);
    //设置录音配置 最长录音时长 以及音量回调的时间间隔
    idealRecorder.setRecordConfig(recordConfig).setMaxRecordTime(60000).setVolumeInterval(100);
    //设置录音时各种状态的监听
    idealRecorder.setStatusListener(statusListener);
    idealRecorder.start(); //开始录音
  }

  @ReactMethod
  public void stop(Callback successCallback) {
    //停止录音
    idealRecorder.stop();
    successCallback.invoke(saveFilePath);
  }

  private void updateMeters(int volume){
    WritableMap event = Arguments.createMap();
    event.putInt("value", volume);

    sendEvent(reactContext, "onRecorderAudioUpdateMeters", event);
  }

  private final StatusListener statusListener = new StatusListener() {
    @Override
    public void onStartRecording() {
    }

    @Override
    public void onRecordData(short[] data, int length) {

    }

    @Override
    public void onVoiceVolume(int volume) {
//      double myVolume = (volume - 40) * 4;
      updateMeters(volume);
      Log.d("rn = ", "current volume is " + volume);
    }

    @Override
    public void onRecordError(int code, String errorMsg) {
      Log.d("rn =",errorMsg);
    }

    @Override
    public void onFileSaveFailed(String error) {
      Log.d("rn =",error.toString());
    }

    @Override
    public void onFileSaveSuccess(String fileUri) {
    }

    @Override
    public void onStopRecording() {
    }
  };

  /**
   * 获取文件保存路径
   *
   * @return saveFilePath
   */
  private String getSaveFilePath() {
    String documentDirectoryPath = getReactApplicationContext().getExternalFilesDir("").getAbsolutePath();
    File file = new File(documentDirectoryPath);
    if (!file.exists()) {
      file.mkdirs();
    }
    File wavFile = new File(file, "audio.wav");
    return wavFile.getAbsolutePath();
  }

  private void sendEvent(ReactContext reactContext,
                         String eventName,
                         @Nullable WritableMap params) {
    reactContext
      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
      .emit(eventName, params);
  }
}
